<script setup>
import { ref } from 'vue'
import { updateCurrentMemberCarService, addCurrentMemberCarService } from '@/api/car.js'

// 控制弹出框的显示与隐藏
const visibleDialog = ref(false)

const defaultDTO = {
  plateNumber: null, // 车牌号
  brand: null, // 车辆品牌
  model: null // 车辆型号
}

const carDTO = ref({ ...defaultDTO })

const plateArray = ref(Array(maxLength).fill('')) // 车牌号码数组
const activeIndex = ref(0) // 当前激活的输入框的索引
const maxLength = 8 // 车牌号码最大长度

// 向外暴露方法
const open = (row) => {
  visibleDialog.value = true // 打开弹出框
  if (row.id) {
    const { id, plateNumber, brand, model } = row
    carDTO.value = { id, plateNumber, brand, model }
    // 初始化车牌号码
    plateArray.value = carDTO.value.plateNumber.split('').slice(0, maxLength)
    if (plateArray.value.length < maxLength) {
      const remainingLength = maxLength - plateArray.value.length
      plateArray.value = plateArray.value.concat(Array(remainingLength).fill(''))
    }
    activeIndex.value = carDTO.value.plateNumber.length - 1
  } else {
    carDTO.value = { ...defaultDTO }
    plateArray.value = Array(maxLength).fill('')
    activeIndex.value = 0
  }
}

// 省份、数字、字母、特殊后缀
const provinces = [
  ['京', '津', '沪', '渝', '冀', '豫', '云', '辽', '黑', '湘'],
  ['皖', '鲁', '新', '苏', '浙', '赣', '鄂', '桂', '甘', '晋'],
  ['蒙', '陕', '吉', '闽', '贵', '粤', '青', '藏', '川', '宁'],
  ['琼', '使', '领']
]
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
const letters = [
  ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
  ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
  ['W', 'X', 'Y', 'Z', '挂', '学', '警', '港', '澳']
]
const specialSuffixs = ['挂', '学', '警', '港', '澳']

// 处理车牌号输入
const handlePlateArrayInput = (char) => {
  if (activeIndex.value < maxLength) {
    plateArray.value[activeIndex.value] = char
    if (activeIndex.value < maxLength - 1) {
      activeIndex.value++
    }
    carDTO.value.plateNumber = plateArray.value.join('')
  }
}

// 处理车牌号删除
const handlePlateArrayDelete = () => {
  if (activeIndex.value >= 0) {
    plateArray.value[activeIndex.value] = ''
    activeIndex.value = Math.max(activeIndex.value - 1, 0)
    carDTO.value.plateNumber = plateArray.value.join('')
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (carDTO.value.id) {
    await updateCurrentMemberCarService(carDTO.value)
    showNotify({
      type: 'success',
      message: '修改成功'
    })
    visibleDialog.value = false
  } else {
    await addCurrentMemberCarService(carDTO.value)
    showNotify({
      type: 'success',
      message: '新增成功'
    })
    visibleDialog.value = false
  }
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDialog.value = false
  carDTO.value = { ...defaultDTO }
  plateArray.value = Array(maxLength).fill('')
  activeIndex.value = 0
}

defineExpose({
  open
})
</script>

<template>
  <van-dialog
    v-model:show="visibleDialog"
    :title="carDTO.id ? '修改车辆信息' : '新增车辆'"
    show-cancel-button
    @confirm="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="license-plate-input">
      <div style="font-size: 14px">请输入车牌号：</div>
      <br />
      <!-- 车牌号码显示 -->
      <div class="plate-display">
        <div
          v-for="(char, index) in plateArray"
          :key="index"
          :class="['plate-box', { active: index === activeIndex }]"
          @click="activeIndex = index"
        >
          {{ char }}
        </div>
      </div>

      <div class="keyboard">
        <!-- 省份（车牌第一位） -->
        <div v-if="activeIndex === 0">
          <div v-for="(row, rowIndex) in provinces" :key="rowIndex" class="keyboard-row">
            <button
              v-for="province in row"
              :key="province"
              @click="handlePlateArrayInput(province)"
            >
              {{ province }}
            </button>
            <button v-if="rowIndex === provinces.length - 1" @click="handlePlateArrayDelete">
              <van-icon name="delete"></van-icon>
            </button>
          </div>
        </div>

        <!-- 数字 -->
        <div v-if="activeIndex !== 0" class="keyboard-row">
          <button
            v-for="number in numbers"
            :key="number"
            @click="handlePlateArrayInput(number)"
            :class="{ disabled: activeIndex <= 1 }"
          >
            {{ number }}
          </button>
        </div>

        <!-- 字母+特殊后缀 -->
        <div v-if="activeIndex !== 0">
          <div v-for="(row, rowIndex) in letters" :key="rowIndex" class="keyboard-row">
            <button
              v-for="letter in row"
              :key="letter"
              @click="handlePlateArrayInput(letter)"
              :class="{ disabled: specialSuffixs.includes(letter) && activeIndex < 6 }"
            >
              {{ letter }}
            </button>
            <button v-if="rowIndex === letters.length - 1" @click="handlePlateArrayDelete">
              <van-icon name="delete"></van-icon>
            </button>
          </div>
        </div>
      </div>
    </div>
    <div>
      <van-cell-group inset>
        <van-field v-model="carDTO.brand" label="车辆品牌" placeholder="请输入车辆品牌" />
        <van-field v-model="carDTO.model" label="车辆型号" placeholder="请输入车辆型号" />
      </van-cell-group>
    </div>
  </van-dialog>
</template>

<style lang="scss" scoped>
.license-plate-input {
  background: #f7f8fa;
  padding: 16px;

  .plate-display {
    display: flex;
    justify-content: center;
    gap: 4px;
    margin-bottom: 20px;
    padding: 0 16px;

    .plate-box {
      width: 40px;
      height: 40px;
      border: 1px solid #ddd;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      background: white;
      cursor: pointer;

      &.active {
        border-color: #1989fa;
        background: #e8f3ff;
      }
    }
  }

  .keyboard {
    .keyboard-row {
      display: flex;
      justify-content: center;
      gap: 4px;
      margin-bottom: 4px;

      button {
        width: 36px;
        height: 44px;
        border: none;
        border-radius: 4px;
        background: white;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        &:active {
          background: #e8e8e8;
        }

        &.disabled {
          color: #ccc;
          pointer-events: none;
        }

        &.function-key {
          width: 80px;
          background: #f2f3f5;
        }
      }
    }

    .provinces-row {
      margin-bottom: 8px;
      button {
        font-size: 14px;
      }
    }
  }
}
</style>
